package com.jjiang.bbmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.jjiang.bbmall.search.config.BbmallElasticSearchConfig;
import com.jjiang.bbmall.search.constant.EsConstant;
import com.jjiang.bbmall.search.service.ProductSaveService;
import com.jjiang.common.to.es.SkuEsModel;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) {
        // 保存到es
        // 1.给es中建立索引：product，建立好映射关系【已成功】
        // 2.为es中保存数据
        BulkRequest bulkRequest = new BulkRequest();
        skuEsModels.forEach(model -> {
            // 构造保存请求
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            // 指定文档的id
            indexRequest.id(model.getSkuId().toString());
            // 放入数据
            indexRequest.source(JSON.toJSONString(model), XContentType.JSON);
            bulkRequest.add(indexRequest);
        });
        try {
            BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, BbmallElasticSearchConfig.COMMON_OPTIONS);
            // TODO 还可以做错误处理
            List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
                return item.getId();
            }).collect(Collectors.toList());
            if (bulk.hasFailures()) {
                log.error("商品上架错误：{}", collect);
                return false;
            }
        } catch (IOException e) {
            log.error(e.getMessage());
            return false;
        }
        return true;
    }
}
